

#include "CityInfo.h"
#include "StdDefs.h"
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#include "XCommon.h"

CCityInfo::CCityInfo()
{
}

CCityInfo::~CCityInfo()
{
}

void CCityInfo::SetDBName(CXString dbName)
{
	m_dbName = dbName;
}

void CCityInfo::GetProvinceList(CXList<CITY_ITEM>* list)
{
	CXString sqlString = "select  provinceID as cityId,province as cityName,'' as cityPostal from Province";
	LoadItemArrayWithSql(list,sqlString);
}

void CCityInfo::GetCityList(CXString itemId,CXList<CITY_ITEM>* list)
{
	CXString sqlString = "select  cityID as cityId,CityName as cityName,'' as cityPostal from City where IsShow=1 and father='";
	sqlString.Append(itemId);
	sqlString.Append("' ");
	LoadItemArrayWithSql(list,sqlString);
}

void CCityInfo::GetAreaList(CXString itemId,CXList<CITY_ITEM>* list)
{
	CXString sqlString = "select  areaID as cityId,area as cityName,PostalCode as cityPostal from Area where IsShow=1 and father='";
	sqlString.Append(itemId);
	sqlString.Append("' ");
	LoadItemArrayWithSql(list,sqlString);
}

void CCityInfo::LoadItemArrayWithSql(CXList<CITY_ITEM>* list,CXString& sqlString)
{
	list->DeleteAll();
	
	sqlite3* db;	
	NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init];

	int result=sqlite3_open(m_dbName.Utf8String(), &db);
	if( SQLITE_OK==result){
		sqlite3_stmt* hydrate_statement=nil;
		const char* sql = sqlString.Utf8String();
		if (sqlite3_prepare_v2(db, sql, -1, &hydrate_statement, NULL) != SQLITE_OK) {
			Common::ShowMsg("sql error",sqlite3_errmsg(db));
		}
		else {
			NSDateFormatter* dateFormatter=[[NSDateFormatter alloc] init];
			[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:SS z"];
			while( SQLITE_ROW==(sqlite3_step(hydrate_statement))){
				const unsigned char *str=NULL;
				CITY_ITEM* item = new CITY_ITEM;
				str = sqlite3_column_text(hydrate_statement, 0);
				item->itemId = (str)?(const char *)str:"";
				
				str = sqlite3_column_text(hydrate_statement, 1);
				item->itemName = (str)?(const char *)str:"";
				
				str = sqlite3_column_text(hydrate_statement, 2);
				item->itemPostal = (str)?(const char *)str:"";
				
				list->AddData(item);
			}
			sqlite3_reset(hydrate_statement);
			result=sqlite3_finalize(hydrate_statement);
			assert(result==SQLITE_OK);
			[dateFormatter release];	
		}
	}
	sqlite3_close(db);
	assert(SQLITE_OK==result);
	[pool release];
}
